package mamikeji.liaowa.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.umeng.analytics.MobclickAgent;

import java.io.InputStream;

import mamikeji.liaowa.R;
import mamikeji.liaowa.application.MyApplication;
import mamikeji.liaowa.bean.Wa_HandWBean;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.widget.statusbar.StatusBarCompat;

/**
 * Created by 廉冲-android开发 on 2017/5/5.
 */
public class BaseActivity extends FragmentActivity {
    private static final String TAG = "BaseActivity";
    public static final int DEFAULT_COLOR = Color.parseColor("#319bd2");
    public Wa_HandWBean WA_HANDW_BEAN = new Wa_HandWBean();
    private Dialog dialog;
    private AnimationDrawable animationDrawable;

    private int LAYOUT_ID;

    protected void getBase() {
        //网络请求动画
        getDialog();
        //记录页面
        MyApplication.getInstance().addActivity(this);
        //沉浸式
        tileColorBar(this);
    }

    private void toggleDialog(boolean bool) {
        if (bool) {
            animationDrawable.start();
            dialog.show();
        } else {
            animationDrawable.stop();
            dialog.dismiss();
        }
    }

    //开
    public void showLoading() {
        toggleDialog(true);
    }

    //关
    public void hideLoading() {
        toggleDialog(false);
    }

    protected void tileBar(Activity activity, Boolean bool) {
        StatusBarCompat.translucentStatusBar(activity, bool);
    }

    protected void tileColorBar(Activity activity) {
//        StatusBarCompat.setStatusBarColor(activity, Color.GREEN);
//        StatusBarCompat.setStatusBarColor(activity, DEFAULT_COLOR);
//        StatusBarCompat.setStatusBarColor(activity, DEFAULT_COLOR, 125);
//        StatusBarCompat.setStatusBarColor(activity, ContextCompat.getColor(activity, R.color.color_app));
//        StatusBarUtil.setColor(Activity activity, int color)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            StatusBarCompat.setStatusBarColor(activity, ContextCompat.getColor(activity, R.color.color_app));
        }else {
            StatusBarUtil.setColor(activity,getResources().getColor(R.color.color_app));
        }
    }

    /**
     * 返回顶部监听
     * @param onClickListener
     */
    protected void getListviewTop(View.OnClickListener onClickListener) {
        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rl_title);
        if (null == relativeLayout) {
            return;
        }
        relativeLayout.setOnClickListener(onClickListener);
    }

    public long timeTop;

    /**
     * 标题左键
     */
    protected void setTitleLeftBtn() {
        ImageView iv = (ImageView) this.findViewById(R.id.iv_header_left);
        if (null == iv) {
            return;
        }
        iv.setImageResource(R.drawable.icon_fanhuibai_n_fff);

        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    /**
     * 标题左键
     */
    protected void setTitleLeftImage(int imgID, View.OnClickListener onClickListener) {
        ImageView iv = (ImageView) this.findViewById(R.id.iv_header_left);
        if (null == iv) {
            return;
        }
        iv.setImageResource(imgID);

        iv.setOnClickListener(onClickListener);
    }

    /**
     * 标题左键图片，点击事件
     */
    protected void setTitleImage(int rId, View.OnClickListener listener) {
        ImageView imageView = (ImageView) findViewById(R.id.iv_header_left);
        imageView.setVisibility(View.VISIBLE);

        if (null == imageView) {
            return;
        }

        imageView.setImageResource(rId);

        if (null != listener) {
            imageView.setOnClickListener(listener);
        }
    }

    /**
     * 设置页面标题名称
     */
    protected void setTitleName(int rId) {
        TextView textView = (TextView) this.findViewById(R.id.tv_header_title);
        if (null == textView) {
            return;
        }
        textView.setVisibility(View.VISIBLE);
        textView.setText(rId);
    }

    /**
     * 设置页面标题名称
     */
    protected void setTitleName(int rId, int color) {
        TextView textView = (TextView) this.findViewById(R.id.tv_header_title);
        if (null == textView) {
            return;
        }
        textView.setTextColor(this.getResources().getColor(color));
        textView.setVisibility(View.VISIBLE);
        textView.setText(rId);
    }

    /**
     * 设置页面标题名称
     */
    protected void setTitleName(String titleName) {
        TextView textView = (TextView) this.findViewById(R.id.tv_header_title);
        if (null == textView) {
            return;
        }
        textView.setVisibility(View.VISIBLE);
        textView.setText(titleName);
    }

    /**
     * 标题右键(文字)
     */
    protected TextView setTitleRightBtn(int rId, View.OnClickListener listener) {
        TextView tv = (TextView) this.findViewById(R.id.rv_header_right);
        tv.setVisibility(View.VISIBLE);

        ImageView imageView = (ImageView) this.findViewById(R.id.iv_header_right);
        imageView.setVisibility(View.GONE);
        if (null == tv) {
            return null;
        }

        tv.setText(rId);
        if (null != listener) {
            tv.setOnClickListener(listener);
        }
        return tv;
    }

    /**
     * 标题右键(文字)
     */
    protected void setTitleRightBtn(int rId, int textColor, View.OnClickListener listener) {
        TextView tv = (TextView) this.findViewById(R.id.rv_header_right);
        tv.setVisibility(View.VISIBLE);

        ImageView imageView = (ImageView) this.findViewById(R.id.iv_header_right);
        imageView.setVisibility(View.GONE);
        if (null == tv) {
            return;
        }

        tv.setText(rId);
        tv.setTextColor(this.getResources().getColor(textColor));
        if (null != listener) {
            tv.setOnClickListener(listener);
        }
    }

    /**
     * 标题右键(图片)
     */
    protected void setTitleRightImage(int rId, View.OnClickListener listener) {
        ImageView imageView = (ImageView) findViewById(R.id.iv_header_right);
        imageView.setVisibility(View.VISIBLE);

        TextView tv = (TextView) this.findViewById(R.id.rv_header_right);
        tv.setVisibility(View.GONE);
        if (null == imageView) {
            return;
        }

        imageView.setImageResource(rId);

        if (null != listener) {
            imageView.setOnClickListener(listener);
        }
    }

    /**
     * 标题背景(图片)
     */
    protected void setTitleBackground(int bgID) {
        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rl_title);
        if (null == relativeLayout) {
            return;
        }
        relativeLayout.setBackgroundResource(bgID);
    }

    //设置身高，体重
    protected void waHeight_weight(String code, int sex, TextView textHeagh, TextView textWeight) {
        setWa_HandW();
        String weightString = getResources().getString(R.string.main_yangyu_width);
        String heighttString = getResources().getString(R.string.main_yangyu_height);

        String weightFinal = "0";
        String heightFinal = "0";

        for (int i = 0; i < WA_HANDW_BEAN.getWa_HandW().size(); i++) {
            String[] temp = null;
            temp = WA_HANDW_BEAN.getWa_HandW().get(i).getCode().split("-");
            int startNum = Integer.parseInt(temp[0]);
            int codeNum = Integer.parseInt(code);
            int endNum = Integer.parseInt(temp[1]);
            if (codeNum >= startNum && codeNum <= endNum) {
                switch (sex) {
                    case 1:
                        weightFinal = String.format(weightString, WA_HANDW_BEAN.getWa_HandW().get(i).getBabyWeight());
                        heightFinal = String.format(heighttString, WA_HANDW_BEAN.getWa_HandW().get(i).getBabyHeight());
                        break;
                    case 0:
                        weightFinal = String.format(weightString, WA_HANDW_BEAN.getWa_HandW().get(i).getGirlWeight());
                        heightFinal = String.format(heighttString, WA_HANDW_BEAN.getWa_HandW().get(i).getGirlHeight());
                        break;
                }
                textWeight.setText(weightFinal);
                textHeagh.setText(heightFinal);
            }
        }
    }

    private void setWa_HandW() {
        try {
            StringBuffer sb_Wa_HandW = new StringBuffer();
            InputStream is = getAssets().open("wa_HandW.json");//打开json数据
            byte[] by = new byte[is.available()];//转字节
            int len = -1;
            while ((len = is.read(by)) != -1) {
                sb_Wa_HandW.append(new String(by, 0, len));//根据字节长度设置编码
            }
            is.close();//关闭流
            WA_HANDW_BEAN = new Gson().fromJson(sb_Wa_HandW.toString(), Wa_HandWBean.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载中的动画
     *
     * @return 将对话框对象直接返回
     */
    public void getDialog() {
        dialog = new Dialog(this, R.style.DialogLoading);
        dialog.setContentView(R.layout.activity_dialogloading);
        dialog.setCanceledOnTouchOutside(false);
        ImageView imageView_progress = (ImageView) dialog.findViewById(R.id.imageView_progress);
        imageView_progress.setBackgroundResource(R.drawable.loading_animlist);
        animationDrawable = (AnimationDrawable) imageView_progress.getBackground();
    }

    /**
     * 判断用户是否登录
     *
     * @return
     */
    public boolean getJudgeLogin() {
        if (ForPreference.getString(ForContents.USER_PHONE).equals("") ||
                ForPreference.getString(ForContents.USER_PHONE) == null) {

            startActivity(new Intent(this, LoginActivity.class));
            return false;

        } else {
            return true;
        }
    }

    /**
     * 高斯模糊
     * @param bitmap
     * @param radius
     * @return
     */
    public Bitmap blur(Bitmap bitmap, float radius) {
        Bitmap output = Bitmap.createBitmap(bitmap); // 创建输出图片
        RenderScript rs = RenderScript.create(this); // 构建一个RenderScript对象
        ScriptIntrinsicBlur gaussianBlue = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); //
        // 创建高斯模糊脚本
        Allocation allIn = Allocation.createFromBitmap(rs, bitmap); // 开辟输入内存
        Allocation allOut = Allocation.createFromBitmap(rs, output); // 开辟输出内存
        gaussianBlue.setRadius(radius); // 设置模糊半径，范围0f<radius<=25f
        gaussianBlue.setInput(allIn); // 设置输入内存
        gaussianBlue.forEach(allOut); // 模糊编码，并将内存填入输出内存
        allOut.copyTo(output); // 将输出内存编码为Bitmap，图片大小必须注意
        rs.destroy(); // 关闭RenderScript对象，API>=23则使用rs.releaseAllContexts()
        return output;
    }

    /**
     * 获取版本号
     * @return
     */
    public String getVersionName(){
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(),0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = packInfo.versionName;
        return version;
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //结束Activity&从集合中移除
        MyApplication.getInstance().closeActivity(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
